﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.DirectoryServices.AccountManagement;

namespace AppFabricAdministrator
{
    public partial class AddUserForm : Form
    {
        private string principalName;
        private bool userFound;
        public AddUserForm()
        {
            InitializeComponent();
        }

        private void btnCheck_Click(object sender, EventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(textBox1.Text))
            {
                if (IsUserInGroup(textBox1.Text) && userFound)
                {
                    this.lblUserPrincipalName.ForeColor = Color.DarkBlue;
                    this.lblUserPrincipalName.Text = "User Found:" + principalName;
                }
                else
                {
                    this.lblUserPrincipalName.ForeColor = Color.DarkRed;
                    this.lblUserPrincipalName.Text = "User not found";
                }
            }
        }
        private bool IsUserInGroup(string userName)
        {
            userFound = false;
            UserPrincipal user = null;
            try
            {
                var cxt = new PrincipalContext(ContextType.Domain);
                user = UserPrincipal.FindByIdentity(cxt, userName);
            }
            catch (Exception ex)
            {
                LogHelper.WriteException(ex);
            }

            if (user == null)
            {
                try
                {
                    var mctx = new PrincipalContext(ContextType.Machine);
                    user = UserPrincipal.FindByIdentity(mctx, userName);
                }
                catch (Exception ex)
                {
                    LogHelper.WriteException(ex);
                }
            }
            if (user != null)
            {
                principalName = user.UserPrincipalName ?? user.SamAccountName;
                userFound = true;
            }
            return userFound;
        }

        public DialogResult ShowAddUserDialog(out string userName)
        {
            if (this.ShowDialog().Equals(DialogResult.OK) && userFound)
            {
                userName = principalName;
                return DialogResult.OK;
            }
            userName = string.Empty;
            return DialogResult.Cancel;
        }
    }
}
